/**
 * @author 太阳当空丶赵
 * @date 2022/12/1-21:08
 * @version 1.0.0
 * userRouter
 */
const express = require("express")
const expressJoi = require("@escook/express-joi")
const jsonwebtoken = require('jsonwebtoken')

const getUUID = require("../utils/getUUID")
const getOpenId = require("../wx/getOpenId")
const getTime = require("../utils/getTime")
const BaseResult = require("../utils/result/BaseResult")

const {feedbackRules} = require("../utils/rules/feedbackRules")
const {userLoginRules} = require("../utils/rules/userLoginRules")
const {secretKey} = require('../config')
const {
    selectAll,
    insertOne
} = require('../database/mapper')

const userRouter = express.Router()

// 用户身份判断
userRouter.all("*",(req,res,nest)=>{
    const {path} = req
    const list = ["/login","/getToken","/getOpenId"]
    if (list.includes(path)) return nest()
    const {userRole} = req.auth
    if (userRole === 0) return nest()
    res.send(BaseResult.userValidateFailed())
})

userRouter.post("/login", expressJoi(userLoginRules), async (req, res) => {
    try {
        const {code} = req.body
        const openId = await getOpenId(code)
        console.info("get codeResult",openId)
        if (!openId) return res.send(BaseResult.userValidateFailed())
        // 获取到用户的openId和sessionKey
        // const {openId} = codeResult
        console.log("get openId",openId)
        const result = (await selectAll("user", {user_id: openId}))[0]
        console.log("get selectUser result", result)
        let data
        if (result) {
            // 如果用户存在，则生成token并返回
            data = {userId: result['user_id'], userRole: result['user_role']}
        } else {
            // 如果用户不存在，则进行添加操作
            const time = getTime()
            await insertOne("user", {user_id: openId,user_role: 0, create_time: time, role_name:"匿名用户"})
            data = {userId: openId, userRole: 0}
        }
        const token = jsonwebtoken.sign(data, secretKey, {expiresIn: "3600s"/*有效时间*/})
        return res.send(BaseResult.success(token))
    } catch (e) {
        res.send(BaseResult.error(e))
    }
})

userRouter.post("/addFeedback", expressJoi(feedbackRules), async (req, res) => {
    const {content, imageUrl} = req.body
    const {userId} = req.auth
    const data = {
        feedback_id: await getUUID(),
        feedback_content: content,
        feedback_image_url: imageUrl,
        user_id: userId,
        feedback_time: getTime()
    }
    await insertOne("feedback", data)
    return res.send(BaseResult.success("success"))
})

userRouter.get("/getFeedbackList",async (req, res) => {
    const {userId} = req.auth
    try {
        const selectResult = await selectAll("feedback", {user_id: userId})
        res.send(BaseResult.success(selectResult.reverse()))
    } catch (e) {
        res.send(BaseResult.error())
    }
})

userRouter.get("/getToken", async (req, res) => {
    try {
        const openId = "7y1230dfasfa32qtf342tsd8q"
        let data = {userId: openId, userRole: 0}
        const token = jsonwebtoken.sign(data, secretKey, {expiresIn: "36000s"/*有效时间*/})
        return res.send(BaseResult.success(token))
    } catch (e) {
        res.send(BaseResult.error())
    }
})

userRouter.get("/getOpenId",(req,res) => {
    console.log(req.headers)
    try {
        res.send(BaseResult.success(req.headers['x-wx-openid']));
    }catch (e){
        res.send(BaseResult.success(JSON.stringify(req.headers)));
    }
})
module.exports = userRouter
